package com.kwan.xframe.util;

import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * Created by Administrator on 2018/3/26.
 */


public class SoketUtil {

	private ExecutorService mExecutorService = null;
	private  String HOST = "192.168.0.26";
	private int PORT = 12000;
	public BufferedSink mSink;
	public BufferedSource mSource;

	public SoketUtil(String host,int port){
		this.HOST = host;
		this.PORT = port;
		init();
	}

	private void init() {
		mExecutorService = Executors.newCachedThreadPool();
	}

	public void connect() {
		mExecutorService.execute(new connectService());
	}

	public void sendString(String sendMsg) {
		mExecutorService.execute(new sendService(sendMsg));
	}

	public void sendByteArray(byte[] data) {
		mExecutorService.execute(new sendByteService(data));
	}

	public void disconnect() {
		mExecutorService.execute(new sendService("0"));
	}

	private class sendService implements Runnable {

		private String msg;

		sendService(String msg) {
			this.msg = msg;
		}

		@Override
		public void run() {

			try {
				mSink.writeUtf8(this.msg + "\n");
				mSink.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	private class sendByteService implements Runnable {

		private byte[] msg;

		sendByteService(byte[] msg) {
			this.msg = msg;
		}

		@Override
		public void run() {

			try {
				mSink.write(this.msg);
				mSink.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



	private class connectService implements Runnable {

		@Override

		public void run() {

			try {
				Socket socket = new Socket(HOST, PORT);
				mSink = Okio.buffer(Okio.sink(socket));
				mSource = Okio.buffer(Okio.source(socket));
				receiveMsg();
			} catch (Exception e) {
				Logger.e(e.getMessage());
			}
		}

	}

	private void receiveMsg() {

		try {

			while (true) {

				for (String receiveMsg; (receiveMsg = mSource.readUtf8Line()) != null; ) {
					Logger.e(receiveMsg);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
